package org.scboy.dbms.utils;

import java.nio.charset.Charset;
import java.util.List;
import java.util.Properties;
import java.util.Set;
import java.util.stream.Collectors;

import org.scboy.dbms.enums.DocType;

import cn.hutool.core.io.IoUtil;

/**
 * 配置文件帮助类
 */
public class ConfigUtil {
	
	Properties props=new Properties();
	
	public static ConfigUtil load(String props,DocType docType) {
		return new ConfigUtil(props,docType);
	}
	
	public ConfigUtil(String props,DocType docType) {
		try {
			if(docType==DocType.PROPERTIES) {
				this.props.load(IoUtil.toStream(props, Charset.defaultCharset()));
			}else {
				this.props=YamlUtil.yamlToProperties(props);
			}
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
	}
	
	/**
	 * 修改配置值
	 * @param key
	 * @param value
	 */
	public void setValue(String key,String value) {
		props.setProperty(key, value);
	}
	
	/**
	 * 获取配置文件内容
	 * @return
	 */
	public String text() {
		Set<String> names = props.stringPropertyNames();
		List<String> nameList = names.stream().sorted().collect(Collectors.toList());
		StringBuilder content=new StringBuilder("");
		for (String key : nameList) {
			String value = props.getProperty(key);	
			String s = key + " = " + value+"\r\n";
			content.append(s);
		}
		return content.toString();
	}
}
